// src/router/index.ts
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import component from "element-plus/es/components/tree-select/src/tree-select-option";
import { useUserStore } from '@/stores/user'
import {ElMessage} from "element-plus";
// 基础路由配置
const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'HomePage',
        redirect: '/index',
        component: () => import('@/views/Layouts/BasicLayout.vue'),// 按需加载组件
        children: [
            {
                path:'/index',
                component: () => import('@/components/Context.vue'),
            },
            {
                path: '/personal-orders',
                name: 'PersonalOrders',
                component:()=>import('@/components/UserOrderManagement.vue'),
            },
            {
                path: '/backend-management/order',
                name: 'BackendManagement',
                meta: { requiresAuth: true, requiresAdmin: true },
                component:()=>import('@/components/BackendManagement.vue'),
                children:[
                    {
                        path:'/backend-management/order',
                        name:'Order',
                        component:()=>import('@/components/OrderManagement.vue'),
                    },
                    {
                        path:'/backend-management/employee',
                        name:'Employee',
                        component:()=>import('@/components/EmployeeManagement.vue'),
                    },
                    {
                        path: '/backend-management/dataAnalysis/order',
                        name: 'DataAnalysis',
                        component:()=>import('@/components/DataAnalysisOrder.vue'),
                    }
                ]
            },

        ]
    },
    {
        path: '/login',
        name: 'Login',
        component:()=>import('@/views/auth/AuthContainer.vue'),
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})


// 全局路由守卫示例
// 修复后的全局路由守卫
router.beforeEach(async (to) => { // 移除未使用的next参数
    const userStore = useUserStore()

    // 如果路由需要管理员权限
    if (to.meta.requiresAdmin) {
        // 坚定登录权限
        if (!userStore.authState) {
            ElMessage.warning('未登录')
            return '/login' // 直接返回重定向路径
        }

        // 获取最新用户信息
        await userStore.fetchUserInfo()

        // 鉴定管理员权限
        if (!userStore.userInfo?.userRole) {
            ElMessage.error('无权限访问管理后台')
            return false // 中止导航
        }
    }

    // 默认放行
    return true
})
export default router